package com.geekstudy.rpc.tool.server;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.LinkedHashMap;
import java.util.Map;

public class RPCServerTool {


    public Map<String, String> serverInvoke(String className, String methodName, Map<String, String> paramMap) {
        Map<String, String> resultMap = new LinkedHashMap<String, String>();

        try {
            Class invokeClass = ClassLoader.getSystemClassLoader().loadClass(className);
            Object target = invokeClass.newInstance();
            Method[] methodArray = invokeClass.getMethods();
            for(Method method : methodArray) {
                if(methodName.equals(method.getName())) {
                    Parameter[] parameterArray = method.getParameters();
                    if(parameterArray == null || parameterArray.length == 0) {
                        method.invoke(target, null);
                    } else {
                        Object[] paramObject = new Object[parameterArray.length];
                        for(int size = 0; size < parameterArray.length; size++) {
                            Parameter param = parameterArray[size];
                            String paramName = param.getName();
                            if(paramMap.containsKey(paramName)) {
                                paramObject[size] = paramMap.get(paramName);
                            } else {
                                paramObject[size] = null;
                            }
                        }
                        Object result = method.invoke(target, paramObject);
                        resultMap.put("result", result.toString());
                    }

                }
            }

        } catch(Exception e) {
            e.printStackTrace();
        }



        return resultMap;
    }
}
